package com.lib.krismile.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.view.WindowManager;

public class SystemUtil {

    public static WindowManager getDisplay(Context context) {
        return (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    }

    /**
     * dp转px
     *
     * @param context
     * @param value
     * @return
     */
    public static float dp2px(Context context, float value) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (value * scale + 0.5f);
    }

    /**
     * dp转px
     *
     * @param context
     * @param value
     * @return
     */
    public static float dp2px(Context context, int value) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (value * scale + 0.5f);
    }

    /**
     * px转dp
     *
     * @param context
     * @param value
     * @return
     */
    public static float px2dp(Context context, float value) {
//        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, context.getResources().getDisplayMetrics());
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (value / scale + 0.5f);
    }

    /**
     * px转dp
     *
     * @param context
     * @param value
     * @return
     */
    public static float px2dp(Context context, int value) {
//        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, context.getResources().getDisplayMetrics());
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (value / scale + 0.5f);
    }

    /**
     * 获取版本 名称
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {

        PackageInfo pi = getPackageInfo(context);
        if (pi == null) {
            return "未知版本";
        }
        return pi.versionName;
    }

    /**
     * 获取版本号
     *
     * @param context
     * @return 版本号
     */
    public static int getVersionCode(Context context) {
        PackageInfo pi = getPackageInfo(context);
        if (pi == null) {
            return 0;
        }
        return pi.versionCode;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;
        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            return pi;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
